package com.leiden.sdk;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.uzmap.pkg.uzcore.UZWebView;
import com.uzmap.pkg.uzcore.uzmodule.ModuleResult;
import com.uzmap.pkg.uzcore.uzmodule.UZModule;
import com.uzmap.pkg.uzcore.uzmodule.UZModuleContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import leiden.interfaces.LeidenConnectResultCallBack;
import leiden.interfaces.LeidenPrintfResultCallBack;
import leiden.interfaces.LeidenScanDeviceCallBack;
import leiden.manager.LeidenManager;
import leiden.manager.connect.LeidenDeviceManager;
import leiden.model.LeidenDevice;
import leiden.model.LeidenEnvPrinterModel;
import leiden.model.LeidenPrinterModel;
import leiden.utils.PermissionUtil;

public class LeidenModule extends UZModule {

    // 操作成功
    static int resultCode = 1;

    static int resultNoLocalPermissions = 2;

    public LeidenModule(UZWebView webView) {
        super(webView);
    }

    // 初始化
    public void jsmethod_init(UZModuleContext uzModuleContext) {
        PermissionUtil.checkPrintfPermission(context());
    }

    // 关闭连接
    public void jsmethod_closeConnect(UZModuleContext uzModuleContext) {
        getLeidenDeviceManager().close();
    }

    // 扫描蓝牙
    public ModuleResult jsmethod_scan(UZModuleContext uzModuleContext) {
        // 位置权限判断
        if (!PermissionUtil.checkLocationPermission(context())) {
            return new ModuleResult(resultNoLocalPermissions);
        }

        LeidenScanDeviceCallBack leidenScanDeviceCallBack = new LeidenScanDeviceCallBack() {
            @Override
            public void scanDevice(LeidenDevice leidenDevice) {
                try {
                    JSONObject params = new JSONObject();
                    params.put("type","devices");
                    params.put("name", leidenDevice.getName());
                    params.put("mac", leidenDevice.getMac());
                    uzModuleContext.success(params,false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void beginScan() {

            }

            @Override
            public void stopScan() {

            }
        };

        Handler handler = new Handler(Looper.getMainLooper());
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    getLeidenDeviceManager().stopScan();
                    JSONObject params = new JSONObject();
                    params.put("type", "end");
                    uzModuleContext.success(params);
                    getLeidenDeviceManager().removeScanDeviceCallBack(leidenScanDeviceCallBack);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        LeidenDeviceManager leidenDeviceManager = getLeidenDeviceManager();
        leidenDeviceManager.addScanDeviceCallBack(leidenScanDeviceCallBack);
        leidenDeviceManager.beginSearch();
        // 每次只扫描十秒
        handler.postDelayed(runnable,10 * 1000);
        return new ModuleResult(resultCode);
    }

    // 连接
    public ModuleResult jsmethod_connect(UZModuleContext uzModuleContext) {

        String mac = uzModuleContext.optString("mac");
        LeidenDeviceManager leidenDeviceManager = getLeidenDeviceManager();

        LeidenConnectResultCallBack leidenConnectResultCallBack = new LeidenConnectResultCallBack() {
            @Override
            public void success(LeidenDevice leidenDevice) {
                try {
                    JSONObject params = new JSONObject();
                    params.put("name",leidenDevice.getName());
                    params.put("mac",leidenDevice.getMac());
                    params.put("result","success");
                    uzModuleContext.success(params);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void close(LeidenDevice leidenDevice) {
                try {
                    JSONObject params = new JSONObject();
                    params.put("name",leidenDevice.getName());
                    params.put("mac",leidenDevice.getMac());
                    params.put("result","close");
                    uzModuleContext.success(params);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(LeidenDevice leidenDevice) {
                try {
                    JSONObject params = new JSONObject();
                    params.put("name",leidenDevice.getName());
                    params.put("mac",leidenDevice.getMac());
                    params.put("result","fail");
                    uzModuleContext.success(params);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };

        leidenDeviceManager.addConnectResultCallBack(leidenConnectResultCallBack);
        boolean connect = leidenDeviceManager.connect(mac);
        return new ModuleResult(connect);
    }

    // 数据发送
    public void jsmethod_writer(UZModuleContext uzModuleContext) {
        try {
            String content = uzModuleContext.optString("content");
            byte[] bytes = content.getBytes(Charset.forName("UTF-8"));
            LeidenDeviceManager leidenDeviceManager = getLeidenDeviceManager();
            int result = leidenDeviceManager.write(bytes);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result", result);
            uzModuleContext.success(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 是否连接方法
    public void jsmethod_isConnect(UZModuleContext uzModuleContext) {
        try {
            boolean connect = getLeidenDeviceManager().isConnect();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result", connect);
            uzModuleContext.success(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 打印方法 图片的路径，如果在Android 10以上，记得放到有权限的地方
    public void jsmethod_printfLabels(UZModuleContext uzModuleContext) {

        try {
            List<LeidenPrinterModel> leidenPrinterModels = new ArrayList<>();

            JSONArray labels = uzModuleContext.optJSONArray("labels");
            for (int i = 0; i < labels.length(); i++) {
                JSONObject labelJSONObject = labels.getJSONObject(i);
                leidenPrinterModels.add(LeidenUtils.createLeidenPrinterModel(labelJSONObject));
            }

            LeidenManager leidenManager = getLeidenManager();
            leidenManager.printfAPLLabels(leidenPrinterModels, new LeidenPrintfResultCallBack() {
                @Override
                public void callBack(int result) {

                    try {
                        /**
                         //打印成功
                         int LEIDEN_PRINTF_RESULT_SUCCESS = 1;
                         //打印错误
                         int LEIDEN_PRINTF_RESULT_CMD_ERROR = 2;
                         //蓝牙未连接
                         int LEIDEN_PRINTF_RESULT_BLUETOOTH = 3;
                         */
                        JSONObject resultJSON = new JSONObject();
                        resultJSON.put("resultType", result);
                        if (result == LeidenPrintfResultCallBack.LEIDEN_PRINTF_RESULT_SUCCESS) {
                            resultJSON.put("result", "打印成功");
                        } else if (result == LeidenPrintfResultCallBack.LEIDEN_PRINTF_RESULT_CMD_ERROR) {
                            resultJSON.put("result", "打印错误");
                        } else if (result == LeidenPrintfResultCallBack.LEIDEN_PRINTF_RESULT_BLUETOOTH) {
                            resultJSON.put("result", "蓝牙未连接");
                        }

                        uzModuleContext.success(resultJSON);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void progress(int total, int progress) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            try {
                JSONObject resultJSON = new JSONObject();
                resultJSON.put("resultType", LeidenPrintfResultCallBack.LEIDEN_PRINTF_RESULT_CMD_ERROR);
                resultJSON.put("result", "打印错误，请检查传入数据是否正常 " + e.getMessage());
                uzModuleContext.success(resultJSON);
            } catch (Exception e1) {
                e.printStackTrace();
            }
        }

    }


    // 设置环境变量
    public void jsmethod_setCurrentEnviron(UZModuleContext uzModuleContext) {
        try {
            LeidenManager leidenManager = getLeidenManager();
            leidenManager.setCurrentEnviron(LeidenUtils.createLeidenEnvPrinterModel(uzModuleContext.asJSONObject()));
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result","success");
            uzModuleContext.success(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("error",e.getMessage());
            } catch (JSONException jsonException) {
                jsonException.printStackTrace();
            }
            uzModuleContext.error(jsonObject);
        }
    }

    // 得到当前环境变量
    public void jsmethod_getCurrentEnviron(UZModuleContext uzModuleContext) {
        try {
            LeidenManager leidenManager = getLeidenManager();
            LeidenEnvPrinterModel leidenEnvPrinterModel = leidenManager.getLeidenEnvPrinterModel();
            JSONObject jsonObject = LeidenUtils.toJSONObject(leidenEnvPrinterModel);
            uzModuleContext.success(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private LeidenManager getLeidenManager() {
        Context context = context();
        return LeidenManager.getInstance(context);
    }


    private LeidenDeviceManager getLeidenDeviceManager() {
        Context context = context();
        return LeidenDeviceManager.getInstance(context);
    }


}
